#include "Avalon/WebServices/HttpServerRequest.hpp"
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>

using namespace Avalon;
using namespace Avalon::IO;
using namespace Avalon::WebServices;
using namespace boost;
using namespace boost::lambda;
using namespace std;

namespace {
  Cookie emptyCookie;
}

HttpServerRequest::HttpServerRequest(const tuple<int, int>& version,
    HttpMethod method, const Uri& uri, const map<string, string>& headers,
    const vector<Cookie>& cookies, const Buffer& body)
    : m_version(version),
      m_method(method),
      m_uri(uri),
      m_headers(headers),
      m_cookies(cookies),
      m_body(body) {}

HttpServerRequest::~HttpServerRequest() {}

const tuple<int, int>& HttpServerRequest::GetVersion() const {
  return m_version;
}

HttpMethod HttpServerRequest::GetMethod() const {
  return m_method;
}

const Uri& HttpServerRequest::GetUri() const {
  return m_uri;
}

const string& HttpServerRequest::GetHeader(const string& name) const {
  static const string NO_HEADER = "";
  map<string, string>::const_iterator headerIterator = m_headers.find(name);
  if(headerIterator == m_headers.end()) {
    return NO_HEADER;
  }
  return headerIterator->second;
}

const map<string, string>& HttpServerRequest::GetHeaders() const {
  return m_headers;
}

const vector<Cookie>& HttpServerRequest::GetCookies() const {
  return m_cookies;
}

const Cookie& HttpServerRequest::GetCookie(const string& name) const {
  vector<Cookie>::const_iterator cookieIterator = find_if(
    m_cookies.begin(), m_cookies.end(), bind(&Cookie::GetName, _1) == name);
  if(cookieIterator == m_cookies.end()) {
    return emptyCookie;
  }
  return *cookieIterator;
}

const Buffer& HttpServerRequest::GetBody() const {
  return m_body;
}
